//
//  GiftDetailViewController.swift
//  ShopIOS
//
//  Created by Apple on 2019/8/8.
//  Copyright © 2019 Apple. All rights reserved.
//

import UIKit

class GiftDetailViewController: UIViewController,UIWebViewDelegate,WRCycleScrollViewDelegate {

    @IBOutlet weak var uv_back: UIView!
    @IBOutlet weak var uv_share: UIView!
    @IBOutlet weak var bannerview: WRCycleScrollView!
    @IBOutlet weak var coin_count: UILabel!
    @IBOutlet weak var lb_price: UILabel!
    @IBOutlet weak var uv_grade: UIView!
    @IBOutlet weak var lb_grade: UILabel!
    @IBOutlet weak var lb_name: UILabel!
    @IBOutlet weak var lb_salecount: UILabel!
    @IBOutlet weak var lb_limit: UILabel!
    @IBOutlet weak var lb_stock: UILabel!
    @IBOutlet weak var lb_exchange: UILabel!
    @IBOutlet weak var webview: UIWebView!
    @IBOutlet weak var uv_content: UIView!
    @IBOutlet weak var scrollview: UIScrollView!
    var popview: ZXPopView!
    var giftId:String!
    var limit:Int!
    var count="1"
    init(giftId:String){
        super.init(nibName: nil, bundle: nil)
        self.giftId=giftId
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        uv_content.snp.makeConstraints { (make) in
            make.width.equalTo(screenW)
        }
        uv_grade.layer.cornerRadius=5
        uv_back.addOnClickListener(target: self, action: #selector(back))
        lb_exchange.addOnClickListener(target: self, action: #selector(pop))
        loaddata()
        // Do any additional setup after loading the view.
    }
    @objc func back(){
        self.navigationController?.popViewController(animated: true)
    }
    func initBanner(serverImages:[String]){
        bannerview.imgsType = .SERVER
        bannerview.serverImgArray = serverImages
        // 添加代理
        bannerview?.delegate = self
    }
    /// 点击图片事件
    func cycleScrollViewDidSelect(at index:Int, cycleScrollView:WRCycleScrollView)
    {
        //        print("点击了第\(index+1)个图片")
    }
    
    /// 图片滚动事件
    func cycleScrollViewDidScroll(to index:Int, cycleScrollView:WRCycleScrollView)
    {
        //        print("滚动到了第\(index+1)个图片")
    }
    func loaddata(){
        var d = ["app_key":app_key,
                 "id":giftId,
                 "userkey":userkey,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        
        AlamofireHelper.get(url: GetGifts, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            let detail=mGiftDetailResult.init(json: res)
            ss.initBanner(serverImages: detail.Images)
            
            let coutString = NSMutableAttributedString.init(string: "\(detail.NeedIntegral)西瓜币")
            coutString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red,range: NSRange(location: 0, length: coutString.length-3))
            coutString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 20),range: NSRange(location: 0, length: coutString.length-3))
            ss.coin_count.attributedText=coutString
            
//            ss.coin_count.text="\(detail.NeedIntegral)西瓜币"
            
            let priceString = NSMutableAttributedString.init(string: "市场价：￥\(detail.GiftValue)")
            priceString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSNumber.init(value: 1), range: NSRange(location: 0, length: priceString.length))
            ss.lb_price.attributedText=priceString
            
//            ss.lb_price.text="市场价：￥\(detail.GiftValue)"
            ss.lb_name.text=detail.GiftName
            ss.lb_salecount.text="已兑：\(detail.SumSales)件"
            ss.limit=Int(detail.ShowLimtQuantity!)
            ss.lb_limit.text="每人限兑：\(detail.ShowLimtQuantity!)件"
            ss.lb_stock.text="库存：\(detail.StockQuantity)"
            
            
            ss.lb_grade.text="\(detail.NeedGradeName!)专享"
//            let textSize = NSString(string: ss.lb_grade.text!).size(withAttributes: [NSAttributedString.Key.font : ss.lb_grade.font!])
//            ss.uv_grade.width=textSize.width+30
            
            if detail.CanBuy{
                ss.lb_exchange.text="立即兑换"
                ss.lb_exchange.backgroundColor = .red
            }else{
                ss.lb_exchange.text=detail.CanNotBuyDes
                ss.lb_exchange.backgroundColor = .gray
            }
            
            
            let html = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "\t<meta charset=\"utf-8\">\n" +
                "\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
                "\t\n" +
                "\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n" +
                "\n" +
                "\t<title>detail</title>\n" +
                "\n" +
                "\t<style>body{border:0;padding:0;margin:0;}img{max-width:100%;border:0;display:block;vertical-align: middle;padding:0;margin:0;}p{border:0;padding:0;margin:0;}div{border:0;padding:0;margin:0;}</style>\n" +
                "</head>"
                + "<body>\(detail.Description!)</body></html>"
            ss.webview.delegate=ss
            ss.webview.loadHTMLString(html, baseURL: nil)
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
//        self.webview.height=webView.scrollView.contentSize.height
//        self.scrollview.contentSize = CGSize(width: screenW, height: webView.scrollView.contentSize.height)
        
        //计算webView内容的高度 然后去改变webView的高度
        
//        let webHeightStr = webView.stringByEvaluatingJavaScript(from: "document.body.scrollHeight")
//        let webHeight = CGFloat((webHeightStr! as NSString).floatValue)
        let webHeight = webView.scrollView.contentSize.height
        print(webHeight)
        self.scrollview.contentSize = CGSize(width: screenW, height: screenW+150 + webHeight)
//        self.webview.frame = CGRect(x: 0, y: screenW+150, width: screenW, height: webHeight)
        self.webview.height=webHeight
        
    }
    
    @objc func pop(){//选择兑换数量
        if popview==nil{
            popview = ZXPopView.init(frame: self.view.bounds)
            let numview=Bundle.main.loadNibNamed("PopGiftNumView", owner: nil, options: nil)?[0]as!PopGiftNumView
            numview.uv_top.layer.cornerRadius=10
            numview.uv_top.clipsToBounds=true
            numview.uv_top.layer.maskedCorners=CACornerMask(rawValue: CACornerMask.layerMinXMinYCorner.rawValue|CACornerMask.layerMaxXMinYCorner.rawValue)
            numview.btn_confirm.addOnClickListener(target: self, action: #selector(confirm))
            numview.btn_num.borderColor(UIColor.lightGray)
            numview.btn_num.maxValue=self.limit
            numview.btn_num.numberResult({ (number) in
                self.count=number
            })
            popview.contenView = numview
            numview.snp.makeConstraints { (make) in
                make.width.equalTo(screenW)
                make.height.equalTo(kSize(width: 120))
                make.bottom.equalTo(kSize(width: 0))
            }
            popview.showInView(view: self.view)
        }else{
            popview.showInView(view: self.view)
        }
        
    }
    @objc func confirm(){//确认兑换
        popview.dismissView()
        self.navigationController?.pushViewController(ConfirmGiftOrderViewController(giftid: giftId, count: count), animated: true)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
